import router from 'next/router';
import { useUrlSearchParams } from 'use-url-search-params';
import { useState } from 'react';
import { Loading } from '@geist-ui/react';
import smartfetch from '@mmstudio/an000058';
import { Button } from 'antd';
import SearchOutlined from '@ant-design/icons/SearchOutlined';

export interface IProps<T> {
	page: number;
	count: number;
	data: T[];
	q: string;
}

/**
 * Search with page number in query
 */
export default function Search<T>({
	initq,
	pagesize,
	service,
	onChange,
	label = '请输入'
}: {
	initq: string;
	pagesize: number;
	service: string;
	onChange(v: IProps<T>): void;
	label?: string;
}) {
	const [q, setq] = useState(initq);
	const [, setParams] = useUrlSearchParams({ q }, { q: String });
	const [searching, setsearching] = useState(false);
	async function search() {
		if (searching) {
			return;
		}
		setsearching(true);
		try {
			const query = router.query;
			setParams({ ...query, q });
			const { data, count } = await smartfetch<{ data: T[]; count: number; }>(service, 'get', {
				...router.query,
				q,
				page: 1,
				pagesize
			});
			onChange({
				count,
				data,
				page: 1,
				q
			});
		} finally {
			setsearching(false);
		}
	}
	return <>
		<div className='cls001'>
			{searching ? <div className='cls004'><Loading>Searching...</Loading></div> : <input className='cls002' type='search' autoFocus value={q} placeholder={label} onChange={(e) => {
				setq(e.target.value);
			}} onKeyPress={(e) => {
				if (e.nativeEvent.key === 'Enter') {
					search();
				}
			}} />}
			<Button shape='round' icon={<SearchOutlined />} disabled={searching} onClick={search}>搜索</Button>
		</div>
		<style jsx>{`
.cls001{
	display: flex;
	justify-content: flex-end;
	margin: 1rem;
}
.cls002, .cls004{
	border-radius: 0.4rem;
	line-height: 1.3rem;
	padding: 0 0.5rem;
	width: 15rem;
	margin-right: 0.5rem;
	border: solid 1px #e0e0e0;
}
.cls002:active,.cls002:focus{
	border: solid 1px gray;
}
`}</style>
	</>;
}
